<template>
  <div>
    <div class="row_block">
      <el-card class="box-card"  style="text-align: center;width: 1000px;" body-style="display: flex;flex-direction: column;justify-content: center;">
        <div slot="header" class="clearfix" style="text-align: center">
          <span>第三方入库</span>
        </div>
        <el-form :model="form" ref="form" label-width="150px" class="formStyle">
          <el-form-item label="卡体类型:" prop="dictCardType">
            <el-radio-group v-model="form.dictCardType">
              <el-radio-button label="CARD">卡入库</el-radio-button>
              <el-radio-button label="DONGLE">设备入库</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择运营商:" prop="channelCompanyId">
            <el-select placeholder="选择运营商" style="width: 300px;" @change="getchannelCompanyId" v-model="channelCompany">
              <el-option v-for="item in form.channelCompanySelect"
                         :key="item.value"
                         :label="item.label"
                         :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择账号:" prop="accountId">
            <el-select size="small" placeholder="选择账号" style="width: 300px;" @change="excelChange" v-model="form.accountId">
              <el-option v-for="item in form.accountSelect"
                         :key="item.id"
                         :label="item.accountName"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择套餐大类:" prop="headId" v-if="isDisplaySetmealHead">
            <el-select size="small" placeholder="请选择套餐大类" style="width: 300px;"
                       v-model="form.headId">
              <el-option v-for="obj in setMealHeads"
                         :key="obj.id"
                         :label="obj.name"
                         :value="obj.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="添加类型：" prop="checked" v-if="form.channelCompanyName=='中天网景'">
            <el-checkbox v-model="form.checked">表单上传</el-checkbox>
          </el-form-item>
          <el-form-item label="添加类型：" prop="radio" v-if="form.channelCompanyId&&form.channelCompanyId!=9&&form.channelCompanyId!=11">
            <el-radio-group v-model="form.radio">
              <el-radio :label="0">模板上传</el-radio>
              <el-radio :label="1">表单上传</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label='下载模板：' v-if="isExcelbutton&&form.radio==0">
            <el-button type="shenda" size="small" @click="downLoadShuolangMuban" :loading="loading" > 下载导入模板<i class="el-icon-download el-icon--right" ></i></el-button>
          </el-form-item>
          <el-form-item label="上传业务号码:" v-if="isExcelbutton&&form.radio==0">
            <div class="file_upload_box">
              <input :append-to-body="false" type="file" ref="key" accept="*" @change="keyChangeHandle(fileList.excel)" class="btnDisplay">
              <el-button type="success">点击上传<i class="el-icon-upload el-icon--right"></i> </el-button>
            </div>
            <div>{{fileName}}</div>
          </el-form-item>
          <el-form-item prop="cardNo" label="卡号：" v-show="form.radio==1||form.checked" >
            <el-input type="textarea" placeholder="请输入卡号" :row="10" v-model="form.cardNo" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item prop="cardIccid" label="iccid：" v-show="form.radio==1||form.checked" >
            <el-input type="textarea" placeholder="请输入iccid" :row="10" v-model="form.cardIccid" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item prop="dongleNum" label="设备号：" v-show="(form.radio==1||form.checked)&&form.dictCardType=='DONGLE'" >
            <el-input type="textarea" placeholder="请输入设备号" :row="10" v-model="form.dongleNum" style="width: 300px;"></el-input>
          </el-form-item>
          <el-form-item prop="cardType" label="运营商：" v-show="form.radio==1||form.checked" >
            <el-select  v-model="form.cardType" placeholder="请选择运营商" style="width: 300px;">
              <el-option v-for="item in cardTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-row v-if="showTableData">
          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%;text-align: center;margin: 20px 0;"
            @selection-change="handleSelectionChange"
            :header-cell-style="{background: $store.state.app.sidebarBgColor, color: '#fff'}">
            <el-table-column
              type="selection"
              width="55"
              align="center">
            </el-table-column>
            <el-table-column
              prop="insertCount"
              label="入库张数"
              align="center">
            </el-table-column>
            <el-table-column
              prop="errorInsertCount"
              label="入库失败张数"
              align="center">
            </el-table-column>
            <el-table-column
              prop="startNum"
              label="开始号码"
              align="center">
            </el-table-column>
            <el-table-column
              prop="endNum"
              label="结束号码"
              align="center">
            </el-table-column>
            <el-table-column
              prop="insertTime"
              label="插入时间"
              align="center">
            </el-table-column>
          </el-table>
          <el-pagination
            background
            @current-change="changePage"
            :current-page="page"
            layout="prev, pager, next,total"
            :page-sizes="pagesize"
            :total="total"
            style="width:100%;text-align: right">
          </el-pagination>
        </el-row>
        <el-row style="text-align: center">
          <el-button @click="toggleSelection" v-if="showTableData">取消选择</el-button>
          <el-button type="primary" v-if="form.radio==1||form.checked" @click="showExl('form')">表格预览</el-button>
          <span v-if="form.radio==1||form.checked" :style="{'color': $store.state.app.sidebarBgColor,'margin-left':'20px'}">注意: 表单提交方式最大可支持3万条数据</span>
          <el-button v-if="!isExcelbutton&&!form.checked" type="primary" @click="submitHandle" v-preventReClick>提 交</el-button>
          <el-button v-if="isExcelbutton&&form.radio==0" type="primary" @click="submitHandleForShuolang" v-preventReClick> 提 交</el-button>
        </el-row>
      </el-card>
      <el-dialog :visible.sync="showExlDialog" title="表格预览" width="50%" center top="5%">
        <el-table :data="exlPageData" border :header-cell-style="{background:$store.state.app.tableBgColor}" :style="{'width': form.dictCardType=='DONGLE'?'700px':'550px','margin': form.dictCardType=='DONGLE'?'0 calc(50% - 350px)':'0 calc(50% - 275px)','position': 'relative'}">
          <el-table-column property="cardNumber" autosize label="卡号" width="200" align="center"></el-table-column>
          <el-table-column property="iccid" autosize label="iccid" width="200" align="center"></el-table-column>
          <el-table-column property="dongleNum" autosize label="设备号" width="150" align="center" v-if="form.dictCardType=='DONGLE'"></el-table-column>
          <el-table-column property="dictOperator" autosize label="运营商" width="150" align="center">
            <template>{{cardTypeName}}</template>
          </el-table-column>
        </el-table>
        <div style="width: 100%;height: 60px;position: relative;display: flex;justify-content: center;align-items: center">
          <el-pagination
            background
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
            :current-page.sync="exlPage"
            :total="total_exl">
          </el-pagination>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showExlDialog = false">关 闭</el-button>
          <el-button v-if="isExcelbutton&&form.radio==1" type="primary" @click="submitHandleForShuolangForm" v-preventReClick> 提 交</el-button>
          <el-button v-if="!isExcelbutton&&form.checked" type="primary" @click="submitHandleForShuolangForm" v-preventReClick> 提 交</el-button>
          <el-button v-if="!isExcelbutton&&!form.checked" type="primary" @click="submitHandle" v-preventReClick>提 交</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {
    listChannelCompany,
    thirdAccountList,
    thirdSelectList,
    batchThirdInventory,
    batchThirdInventoryForShuolang,
    batchThirdInventoryForShuolangForm,
    initSetMealHeadList
  } from '@/api/getData'

  export default {
    name: "index",
    data() {
      return {
        isDisplaySetmealHead: false,
        isExcelbutton: false,//硕郎提交入库数据
        channelCompany:'',
        cardTypeName: '',
        form: {
          channelCompanySelect: [],
          accountSelect: [],
          accountId: '',
          channelCompanyId: '',
          channelCompanyName: '',
          addArr: [],
          cardNumberStart: '',
          headId: '',
          radio: 0,
          checked: false,
          cardNo: '',
          cardIccid: '',
          dongleNum: '',
          cardType: '',
          dictCardType: 'CARD',
        },
        fileList: {
          excel: ""
        },
        fileName: "",
        fileType: "",
        setMealHeads:[],
        dictSetMealGroupType:'',
        pagekey: '',
        list: [],
        multipleTable: [],
        tableData: [],
        loading: false,
        tablePage: 0,
        page: 1,
        pagesize:10,
        total: 0,
        totalPage: 1,
        showTableData: false,
        showExlDialog: false,
        exlData: [],
        exlPageData: [],
        cardTypeOptions: [
          { label:'请选择', value: '' },
          { label:'移动', value: '1' },
          { label:'电信', value: '2' },
          { label:'联通', value: '3' },
        ],
        exlPage: 1,
        exlPageSize: 10,
        total_exl: 0,
      }
    },
    async created() {
      listChannelCompany().then(v => {
        v.data.map(item=>{
          let obj = {};
          obj.value = item.id;
          obj.label = item.operatorBranch;
          obj.commonsTemplate = item.commonsTemplate;
          this.form.channelCompanySelect.push(obj)
        })
      })

      this.pagekey = await await this.$getPageKey();
    },
    methods: {
      handleCurrentChange(val){
        this.exlPage = val;
        let a = 10 * (val - 1);
        let b = 10 * val;
        if(b+1>this.exlData.length)b=this.exlData.length;
        this.exlPageData = [];
        this.exlPageData = this.exlData.slice(a,b);
      },
      //展示用户录入的exl
      showExl(formName) {
        let _this = this;
        if (!this.form.cardNo) {
          this.$message.error('请输入卡号');
          return false;
        }
        if (!this.form.cardIccid) {
          this.$message.error('请输入iccid');
          return false;
        }
        if (!this.form.dongleNum&&this.form.dictCardType=='DONGLE') {
          this.$message.error('请输入iccid');
          return false;
        }
        if (!this.form.cardType) {
          this.$message.error('请选择运营商');
          return false;
        }
        let arr_cardNo = this.form.cardNo.split('\n');
        arr_cardNo = arr_cardNo.filter(function (s) {
          return s && s.replace(/(^\s*)|(\s*$)/g, "");
        });
        let arr_iccid = this.form.cardIccid.split('\n');
        arr_iccid = arr_iccid.filter(function (s) {
          return s && s.replace(/(^\s*)|(\s*$)/g, "");
        });
        let arr_dongle = [];
        if(this.form.dongleNum&&this.form.dictCardType=='DONGLE'){
          arr_dongle = this.form.dongleNum.split('\n');
          arr_dongle = arr_dongle.filter(function (s) {
            return s && s.replace(/(^\s*)|(\s*$)/g, "");
          });
        }
        if(arr_cardNo.length!=arr_iccid.length){
          this.$message.error('您录入的卡号与iccid数量不同，请检查');
          return false;
        }
        let cardType = '';
        this.cardTypeOptions.map(function (item){
          if(item.value==_this.form.cardType){
            _this.cardTypeName = item.label;
            switch (item.label){
              case "电信":
                cardType = 'CARDTELECOM';
                break;
              case "移动":
                cardType = 'CARDMOBILE';
                break;
              case "联通":
                cardType = 'CARDUNICOM';
                break;
            }
          }
        });
        this.exlData = [];
        arr_cardNo.forEach((item,i)=>{
          let obj = {};
          obj.cardNumber = item.replace(/(^\s*)|(\s*$)/g, "");
          obj.iccid = arr_iccid[i].replace(/(^\s*)|(\s*$)/g, "");
          if(this.form.dictCardType=='DONGLE'){
            obj.dongleNum = arr_dongle[i].replace(/(^\s*)|(\s*$)/g, "");
          }
          obj.dictOperator = cardType;
          this.exlData.push(obj)
        })
        this.exlPage = 1;
        this.total_exl = this.exlData.length;
        this.exlPageData = this.exlData.slice(0,10);
        this.showExlDialog = true;
      },
      getFile(event) {
        var file = event.target.files;
        for (var i = 0; i < file.length; i++) {
          //上传类型判断
          var imgName = file[i].name;
          var idx = imgName.lastIndexOf(".");
          if (idx != -1) {
            var ext = imgName.substr(idx + 1).toUpperCase();
            ext = ext.toLowerCase();
            this.form.addArr.push(file[i]);
          }
        }
      },
      async getThirdList(){
        let returnData = await thirdSelectList({id: this.form.accountId});
        this.page = 1;
        if(returnData._result){
          this.list = new Array(...returnData.data);
          let list = new Array(...returnData.data).splice(0,10);
          this.tableData = list;
          this.total = this.list.length;
          this.totalPage = this.total / 10;
          if(this.total % 10 > 0){
            this.totalPage ++;
          }
        }
      },
      changePage(val){
        this.page = val;
        let n = ( val - 1 ) * 10;
        if(n<0){
          n=0
        }
        let m = 10;
        let list = new Array(...this.list);
        if(val===this.totalPage){
          m = this.total - 10 * n;
        }
        this.tableData = list.splice(n,m);
      },
      handleSelectionChange(val){
        this.multipleTable = val
      },
      toggleSelection(){
        this.$refs.multipleTable.clearSelection();
      },
      keyChangeHandle(fileList) {
        if (fileList !== '') {
          return false
        } else {
          this.fileList.excel = this.$refs.key.files[0]
          if (this.$refs.key.files[0] != null) {
            this.fileName = this.$refs.key.files[0].name;
            this.fileType = this.fileName.substring(this.fileName.lastIndexOf('.')+1,this.fileName.length);
          }
        }
      },
      async getchannelCompanyId(val) {
        this.form.channelCompanyId = val.value;
        this.form.channelCompanyName = val.label;
        this.showTableData = false;
        if (val.commonsTemplate=="C_YES") {
          this.isExcelbutton = true;
          this.isDisplaySetmealHead = true;
          this.form.headId = '';
        } else {
          this.isExcelbutton = false;
          this.isDisplaySetmealHead = false
        }
        const a = await thirdAccountList({
            channelCompanyId: this.form.channelCompanyId
          }
        )
        if (a._result) {
          this.form.accountSelect = a.data;
        }
        //获取到套餐大类数据
        if(this.form.channelCompanyId == 10){
          // this.dictSetMealGroupType = 'SHUOLANG_HEAD';
          // initSetMealHeadList({dictSetMealGroupType:'SHUOLANG_HEAD'}).then(v=>{
          //   this.setMealHeads = v.data
          // })
          this.dictSetMealGroupType = 'TONGYONG_HEAD';
          initSetMealHeadList({dictSetMealGroupType:'TONGYONG_HEAD'}).then(v=>{
            this.setMealHeads = v.data
          })
        }
        else if(this.form.channelCompanyId == 12){
          // this.dictSetMealGroupType = 'MEILI_HEAD';
          // initSetMealHeadList({dictSetMealGroupType:'MEILI_HEAD'}).then(v=>{
          //   this.setMealHeads = v.data
          // })
          this.dictSetMealGroupType = 'TONGYONG_HEAD';
          initSetMealHeadList({dictSetMealGroupType:'TONGYONG_HEAD'}).then(v=>{
            this.setMealHeads = v.data
          })
        }
        else if(this.form.channelCompanyId == 13){
          // this.dictSetMealGroupType = 'LONGWANG_HEAD';
          // initSetMealHeadList({dictSetMealGroupType:'LONGWANG_HEAD'}).then(v=>{
          //   this.setMealHeads = v.data
          // })
          this.dictSetMealGroupType = 'TONGYONG_HEAD';
          initSetMealHeadList({dictSetMealGroupType:'TONGYONG_HEAD'}).then(v=>{
            this.setMealHeads = v.data
          })
        }
        else{//否则就是通用
          this.dictSetMealGroupType = 'TONGYONG_HEAD';
          initSetMealHeadList({dictSetMealGroupType:'TONGYONG_HEAD'}).then(v=>{
            this.setMealHeads = v.data
          })
        }
        this.form.accountId = ''

      },
      excelChange(val) {
        this.form.accountId = val;
        this.form.headId = '';
        if(this.form.channelCompanyName=='申达'){
          this.showTableData = true;
          this.getThirdList();
        }
        // for(let item of this.form.channelCompanySelect){
        //   if(_this.form.channelCompanyId === item.id && item.operatorBranch==='申达'){
        //     _this.showTableData = true;
        //     _this.getThirdList();
        //     return ;
        //   }
        //   else{
        //     this.showTableData = false;
        //   }
        // }
      },

      submitHandle() {
        if (this.form.accountId == '') {
          this.$message.error("请选择账号！")
          return
        }

        if(this.showTableData&&this.multipleTable.length===0){
          this.$message.error("请选择一条数据！")
          return
        }
        if(this.showTableData&&this.multipleTable.length>1){
          this.$message.error("每次只能选择一条数据！")
          return
        }
        this.$message.warning("入库中！")
        let id = '';
        if(this.showTableData&&this.multipleTable.length>0){
          id = this.multipleTable[0].id;
        }
        batchThirdInventory({
          channelCompanyId:this.form.channelCompanyId,
          accountId: this.form.accountId,
          cardNumberStart: this.form.cardNumberStart,
          outBoundId: id,
          cardList: this.exlData,
          inventoryType: this.form.dictCardType,
        },{pagekey: this.pagekey}).then(async v => {
          if (v.code == 10000) {
            this.$message.success("入库成功！");
            this.$router.push({path: '/Stock/stockInList' });
          } else {
            this.$message.error("入库失败！")
          }
          this.pagekey = await this.$getPageKey();
        })
      },

      submitHandleForShuolang() {
        if (this.form.accountId == '') {
          this.$message.error("请选择账号！")
          return
        }
        if (this.form.channelCompanyId == 10 && this.fileName == "" && this.form.radio==0) {
          this.$message.error("请选择文件")
          return
        }
        if(this.fileType!=='xls'&&this.fileType!=='xlsx'&& this.form.radio==0){
          this.$message.error("您上传的文件格式错误，只能上传表格文件！")
          return
        }
        if(this.showTableData&&this.multipleTable.length===0){
          this.$message.error("请选择一条数据！")
          return
        }
        if(this.showTableData&&this.multipleTable.length>1){
          this.$message.error("每次只能选择一条数据！")
          return
        }
        let loading = this.$loading({
          lock: true,
          text: '数据提交中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        // this.$message.warning("入库中！")
        let id = '';
        if(this.showTableData&&this.multipleTable.length===0){
          id = this.multipleTable[0].id;
        }

        batchThirdInventoryForShuolang({
          channelCompanyId:this.form.channelCompanyId,
          dictSetMealGroupType:this.dictSetMealGroupType,
          accountId: this.form.accountId,
          file: this.fileList.excel,
          outBoundId: id,
          setMealHeadId: this.form.headId,
          inventoryType: this.form.dictCardType,
        },{pagekey: this.pagekey}).then(async v => {
          loading.close();
          if (v.code === 10000) {
            this.$message.success("入库成功！");
            this.$router.push({path: '/Stock/stockInList' });
          } else {
            this.$message.error("入库失败！")
          }
          this.showExlDialog = false;
          this.pagekey = await this.$getPageKey();
          this.$nextTick(function (){
            this.resetForm()
          })
        })
      },
      resetForm(){
        this.$refs.form.resetFields();
        this.form.channelCompanyId = ''
        this.form.channelCompanyName = ''
        this.channelCompany = {value: '',label:'',commonsTemplate: ''}
        this.isExcelbutton = false
        this.isDisplaySetmealHead = false
      },
      submitHandleForShuolangForm(){
        if (this.form.accountId == '') {
          this.$message.error("请选择账号！")
          return false
        }
        this.fullscreenLoading = true;
        let loading = this.$loading({
          lock: true,
          text: '数据提交中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        batchThirdInventoryForShuolangForm({
          channelCompanyId:this.form.channelCompanyId,
          setMealHeadId:this.form.headId,
          accountId: this.form.accountId,
          cardList: this.exlData,
          inventoryType: this.form.dictCardType,
        },{pagekey: this.pagekey}).then(async v => {
          if (v.code === 10000) {
            this.$message.success("入库成功！");
            this.$router.push({path: '/Stock/stockInList' });
          } else {
            this.$message.error("入库失败！")
          }
          loading.close();
          this.pagekey = await this.$getPageKey();
        })
      },
      downLoadShuolangMuban(){
        let href = '';
        if(this.form.dictCardType=='CARD'){
          href = "https://imgsd.1688iot.vip/sanfang_tongyong.xlsx";
        }
        if(this.form.dictCardType=='DONGLE'){
          href = "https://imgsd.1688iot.vip/%E8%AE%BE%E5%A4%87%E9%80%9A%E7%94%A8%E5%85%A5%E5%BA%93%E6%A8%A1%E6%9D%BF.xlsx";
        }
        window.open(href, '_blank');
      }
    },


  }
</script>


<style scoped>
  .file_upload_box {
    display: inline-block;
    width: 200px;
    height: auto;
    position: relative;
    overflow: hidden;
  }

  .file_upload_box a {
    display: inline-block;
    width: 50%;
    line-height: 25px;
    text-align: center;
    font-family: "Microsoft yahei";
    background-color: #315baf;
    color: #FFF;
    font-weight: 700;
    text-decoration: none;
  }
  .row_block {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 70px 0;
  }
  .formStyle{
    width: 500px;
    height: auto;
    margin: 10px 350px 20px 150px;
  }
  .btnDisplay{
    width: 100px;
    height: 40px;
    position: absolute;
    left: 50px;
    top: 0;
    opacity: 0;
    cursor: pointer;
  }
</style>
